<?php

namespace App\Jobs;

use App\Article;
use App\Image;
use App\Jobs\Job;
use App\Tag;
use GuzzleHttp\Client;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Symfony\Component\DomCrawler\Crawler;

class FetchDygodPageIJob extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;
    protected $client;
    protected $host = 'www.dy2018.com';
    protected $href;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($href)
    {
        $this->href = $href;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if ($this->attempts() > 2) {
            $this->delete();
            return;
        }
        $base_url = 'http://'.$this->host;
        $headers = config('app.google_bot_headers');
        $headers['host'] = $this->host;
        $this->client = new Client([ 'headers'=>$headers, 'base_uri' => $base_url]);
        $res = $this->client->request('GET',$this->href);
        $html = $res->getBody()->getContents();
        $crawler = new Crawler($html);
        $body = $crawler->filter('#Zoom')->html();
        var_dump(strlen($body));

        $title = $crawler->filter('div.title_all > h1')->text();
        $keyword = $crawler->filter('head > meta[name="keywords"]')->first()->attr('content');

        $full_url = $base_url.$this->href;
        $attr = ['url_provider'=>$full_url];

        $values = ['body'=>$body,'title'=>$title,'key_word'=>$keyword];
        $article = Article::updateOrNew($attr);
        $article->timestamps = false;
        $article->fill($values);

//        $images = [];
//        $crawler->filter('#Zoom img')->each(function(Crawler $row,$i) use($article,&$images) {
//            $alt = $row->attr('alt');
//            $src = $row->attr('src');
//            $key = base64_encode($this->href).$i;
//            $image = Image::fetchUrlWithKey($src,$key,$alt);
//            $replacement = $image->imgURL();
//            $article->body = str_ireplace($src,$replacement,$article->body);
//            var_dump($article->body);
//
//            $article->save();
//            $images[] = $image;
//        });
//        $article->images()->saveMany($images);
        $tag = Tag::find(24);
        $article->tags()->save($tag);
        $article->save();

    }
}
